package org.tgcloud.group.service.manager;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.tgcloud.group.core.*;
import org.tgcloud.group.entity.*;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.service.manager.notify.NotifyService;
import org.tgcloud.group.service.manager.process.ProcessManageService;
import org.tgcloud.group.service.manager.project.FileManageService;
import org.tgcloud.group.service.manager.project.ProjectIntendedMediaManageService;
import org.tgcloud.group.service.manager.project.ProjectMediaRequirementsManageService;
import org.tgcloud.group.service.manager.project.ProjectStageService;
import org.tgcloud.group.service.task.SendSubscribeMsgTask;
import org.tgcloud.group.web.controller.dto.medium.*;
import org.tgcloud.group.web.controller.dto.order.ProjectListDTO;
import org.tgcloud.group.web.controller.dto.process.ProcessToUser;
import org.tgcloud.group.web.controller.manager.process.enums.ProcessEnum;
import org.tgcloud.group.web.controller.req.project.ProjectEditReq;
import org.tgcloud.group.web.controller.req.project.ProjectIdReq;
import org.tgcloud.group.web.controller.req.project.ProjectPageReq;
import org.tgcloud.group.web.controller.req.project.intendedMedia.ProjectAddIntendedMediaReq;
import org.tgcloud.group.web.controller.req.project.mediaRequirements.MediaRequirementsBatchCreateReq;
import org.tgcloud.group.web.controller.req.project.mediaRequirements.MediaRequirementsCreateReq;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: zhy
 * @create: 2023-08-18 10:03
 * @description:
 */
@Service
public class ProjectManageService {

    @Autowired
    private MjProjectMapper projectMapper;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjOrderMapper orderMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    @Autowired
    private SendSubscribeMsgTask sendSubscribeMsgTask;

    @Autowired
    private MjProjectMediumMapper projectMediumMapper;

    @Autowired
    private MjMediumOnlineMapper mediumOnlineMapper;

    @Autowired
    private MjMediumOfflineMapper mediumOfflineMapper;

    @Autowired
    private MjBusinessAccountMapper businessAccountMapper;

    @Autowired
    private MjProjectBatchMapper projectBatchMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private MjUserOrderStatusMapper mjUserOrderStatusMapper;

    @Autowired
    private LogOperateMapper logOperateMapper;

    @Autowired
    private MediumOtherProjectManageService mediumOtherProjectManageService;

    @Autowired
    private ProcessManageService processManageService;

    @Autowired
    private ProjectIntendedMediaMapper projectIntendedMediaMapper;

    @Autowired
    private ProjectIntendedMediaManageService projectIntendedMediaManageService;

    @Autowired
    private ProjectMediaRequirementsManageService projectMediaRequirementsManageService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private ProjectUserMapper projectUserMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private MjProjectStageMapper projectStageMapper;

    @Autowired
    private FileManageService fileManageService;

    public APPResultMessage<Object, ProjectListDTO> getProjectManageList(ProjectPageReq req, int userId, String roleIds) {
        Integer managerUserId = null;
        if (StringUtil.isNotBlank(roleIds) && StringUtil.containsString(roleIds.split(","), "50")) {
            managerUserId = userId;
        }
        // 判断是否是商务账户
        if (StringUtil.isNotBlank(roleIds) && (StringUtil.containsString(roleIds.split(","), "40") || StringUtil.containsString(roleIds.split(","), "55"))) {
            req.setBusinessId(userId);
        }
        if (req.getPageNum() != null && req.getPageSize() != null) {
            PageHelper.startPage(req.getPageNum(), req.getPageSize());
            List<ProjectListDTO> listDTOS = projectMapper.selectList(req.getKeyword(), managerUserId, req.getExecutionProgressId(), req.getArrivalProgressId(),
                    req.getArrivalWarehouseId(), req.getIsDiscount(), req.getPermissionId(), req.getBusinessId(), req.getAreaId(), req.getCateIds(),
                    req.getProjectId(), req.getStatus(), req.getIsTimeOut());
            PageInfo<ProjectListDTO> tables = new PageInfo<>(listDTOS);
            for (ProjectListDTO dto : tables.getList()) {
                if (StringUtil.isNotBlank(dto.getAreaId())) {
                    String areaIds = dto.getAreaId();
                    String areaName = "";
                    for (String areaId : areaIds.split(",")) {
                        SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(areaId));
                        areaName = areaName + labelValue.getSysValueName() + ";";
                    }
                    dto.setAreas(areaName);
                }
                if (StringUtil.isNotBlank(dto.getCateIds())) {
                    String cateIds = dto.getCateIds();
                    String name = "";
                    for (String id : cateIds.split(",")) {
                        SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                        name = name + labelValue.getSysValueName() + ";";
                    }
                    dto.setCates(name);
                }
                //查询推送的人
                if (StringUtil.isNotBlank(dto.getPushUserIds())) {
                    StringBuilder userNamesBuilder = new StringBuilder();
                    StringBuilder assistantNamesBuilder = new StringBuilder();

                    for (String pushUserId : dto.getPushUserIds().trim().split(",")) {
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            //判断是否助理
                            if (mjNormalUser.getIsAssistant() == (short) 1) {
                                if (userNamesBuilder.length() > 0) {
                                    userNamesBuilder.append(",");
                                }
                                userNamesBuilder.append(mjNormalUser.getNickName());
                            } else if (mjNormalUser.getIsAssistant() == (short) 2) {
                                if (assistantNamesBuilder.length() > 0) {
                                    assistantNamesBuilder.append(",");
                                }
                                assistantNamesBuilder.append(mjNormalUser.getNickName());
                            }

                        }
                    }
                    dto.setPushUserName(userNamesBuilder.toString());
                    dto.setPushAssistantName(assistantNamesBuilder.toString());
                }
                // 查询转移转推的开拓者
                if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 && StringUtil.isNotBlank(dto.getNextPushUserIds())) {
                    String[] split = dto.getNextPushUserIds().split(",");
                    List<String> nextPushNames = new ArrayList<>();
                    List<String> nextPushAssistants = new ArrayList<>();

                    for (String nextPushUserId : split) {
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            //判断是否助理
                            if (mjNormalUser.getIsAssistant() == (short) 1) {
                                nextPushNames.add(mjNormalUser.getNickName());
                            } else if (mjNormalUser.getIsAssistant() == (short) 2) {
                                nextPushAssistants.add(mjNormalUser.getNickName());
                            }

                        }
                    }
//                    List<String> userNames = normalUserMapper.selectUserNameByIds(split);
                    dto.setNextPushUserNames(nextPushNames);
                    dto.setNextPushAssistantNames(nextPushAssistants);
                }

            }
            ResultMessage resultMessage = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        } else {
            List<ProjectListDTO> listDTOS = projectMapper.selectList(req.getKeyword(), managerUserId, req.getExecutionProgressId(), req.getArrivalProgressId(),
                    req.getArrivalWarehouseId(), req.getIsDiscount(), req.getPermissionId(), req.getBusinessId(), req.getAreaId(), req.getCateIds(),
                    req.getProjectId(), req.getStatus(), req.getIsTimeOut());
            for (ProjectListDTO dto : listDTOS) {
                if (StringUtil.isNotBlank(dto.getAreaId())) {
                    String areaIds = dto.getAreaId();
                    String areaName = "";
                    for (String areaId : areaIds.split(",")) {
                        SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(areaId));
                        areaName = areaName + labelValue.getSysValueName() + ";";
                    }
                    dto.setAreas(areaName);
                }
                if (StringUtil.isNotBlank(dto.getCateIds())) {
                    String cateIds = dto.getCateIds();
                    String name = "";
                    for (String id : cateIds.split(",")) {
                        SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                        name = name + labelValue.getSysValueName() + ";";
                    }
                    dto.setCates(name);
                }
                // 查询转移转推的开拓者
                if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 && dto.getNextPushUserIds() != null) {
                    String[] split = dto.getNextPushUserIds().split(",");
                    List<String> userNames = normalUserMapper.selectUserNameByIds(split);
                    dto.setNextPushUserNames(userNames);
                }
            }
            ResultMessage resultMessage = ResultMessage.builder().setList(listDTOS);
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage<Object, List> editManageProject(ProjectEditReq req, Integer userId, Short userType) {
//        MjProject mjProject = projectMapper.selectMsgByNameAndId(req.getProjectName(), req.getId());
//        if (mjProject != null){
//            return new APPResultMessage<>(6001, "该项目名称已被使用");
//        }
        MjProject project = req;
        project.setUpdateTime(new Date());
        if (req.getBusinessId() != null) {
            MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(req.getBusinessId());
            project.setBussinessUsername(businessPerson.getUsername());
        }
        if (req.getPermissionId() != null) {
            SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(req.getPermissionId());
            project.setPermissionUsername(managerUser.getUsername());
        }
        if (req.getBrandId() != null) {
            project.setBrandId(req.getBrandId());
        }
        if (StringUtil.isNotBlank(req.getBrandPlacement())) {
            project.setBrandPlacement(req.getBrandPlacement());
        }
        if (StringUtil.isNotBlank(req.getBrandPlacementPic())) {
            project.setBrandPlacementPic(req.getBrandPlacementPic());
        }
        //项目已到货百分比
        Integer sumRate = projectBatchMapper.selectArriveRateSum(project.getId());
        if (sumRate != null) {
            //如果要新增的百分比加上已到货百分比不大于100责可以新增
            if (req.getArrivalProgressId() != null && req.getArrivalRate() != null) {
                if (req.getArrivalRate().add(new BigDecimal(sumRate)).compareTo(BigDecimal.valueOf(100)) <= 0) {
                    if (req.getArrivalProgressId() == 435 || req.getArrivalProgressId() == 434) {
                        MjProjectBatch mjProjectBatch = new MjProjectBatch();
                        mjProjectBatch.setProjectId(req.getId());
                        Integer batchMax = projectBatchMapper.selectProjectBatchMax(req.getId());
                        // 判断是否已有批次
                        if (batchMax != null) {
                            batchMax = batchMax + 1;
                            //设定批次
                            mjProjectBatch.setProjectBatchId(batchMax);
                        }
                        mjProjectBatch.setArrivalTime(req.getArrivalTime());
                        project.setArrivalProgressId(req.getArrivalProgressId());
                        mjProjectBatch.setArrivalProgressId(req.getArrivalProgressId());
                        mjProjectBatch.setArrivalInnerPrice(req.getArrivalInnerPrice());
                        mjProjectBatch.setArrivalRate(req.getArrivalRate());
                        mjProjectBatch.setStatus((short) 1);
                        //新增
                        projectBatchMapper.insertSelective(mjProjectBatch);
                    }
                } else {
                    return new APPResultMessage(6001, "到货百分比不可超过100");
                }
            }
        } else {
            if (req.getArrivalProgressId() != null && req.getArrivalRate() != null) {
                if (req.getArrivalRate().compareTo(BigDecimal.valueOf(100)) <= 0) {
                    //如果要新增的百分比不大于100责可以新增
                    if (req.getArrivalRate().compareTo(BigDecimal.valueOf(100)) <= 0) {
                        if (req.getArrivalProgressId() == 435 || req.getArrivalProgressId() == 434) {
                            MjProjectBatch mjProjectBatch = new MjProjectBatch();
                            mjProjectBatch.setProjectId(req.getId());
                            Integer batchMax = projectBatchMapper.selectProjectBatchMax(req.getId());
                            // 判断是否已有批次
                            if (batchMax != null) {
                                batchMax = batchMax + 1;
                                //设定批次
                                mjProjectBatch.setProjectBatchId(batchMax);
                            }
                            mjProjectBatch.setArrivalTime(req.getArrivalTime());
                            project.setArrivalProgressId(req.getArrivalProgressId());
                            mjProjectBatch.setArrivalProgressId(req.getArrivalProgressId());
                            mjProjectBatch.setArrivalInnerPrice(req.getArrivalInnerPrice());
                            mjProjectBatch.setArrivalRate(req.getArrivalRate());
                            mjProjectBatch.setStatus((short) 1);
                            //新增
                            projectBatchMapper.insertSelective(mjProjectBatch);
                        }
                    }

                } else {
                    return new APPResultMessage(6001, "到货百分比不可超过100");
                }
            }

        }


        projectMapper.updateByPrimaryKeySelective(project);
        if (StringUtil.isNotBlank(req.getBrands())) {
            orderMapper.updateBrandsByProjectId(req.getId(), req.getBrands());
        }

        // 添加进程
//        processManageService.doAddProcess(project.getId(), userId, userType, ProcessEnum.editProject, null);

        return APPResultMessage.getSuccessMessage();
    }

    @Transactional
    public APPResultMessage<Object, List> addOnlyProject(ProjectEditReq req, Integer userId, Short userType) {

        MjProject project = new MjProject();
        project.setName(req.getName());
        project.setProjectName(req.getProjectName());
        project.setBrands(req.getBrands());
        project.setBrandsUsername(req.getBrandsUsername());
        project.setCateIds(req.getCateIds());
        project.setBussinessUsername(req.getBussinessUsername());
        project.setBusinessId(req.getBusinessId());
        project.setAreaId(req.getAreaId());
        project.setPermissionUsername(req.getPermissionUsername());
        project.setPermissionId(req.getPermissionId());
        project.setCreateTime(new Date());
        project.setStatus((short) 1);
        project.setProductName(req.getProductName());
        project.setProjectType(req.getProjectType());
        if (StringUtil.isNotBlank(req.getBrands())) {
            MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddByBrandsNameAndNoBrandId(req.getBrands(), req.getBusinessId());
            if (mjBusinessAccount != null) {
                return new APPResultMessage(6003, "该品牌处于受保状态，无法添加项目");
            }
            MjBusinessAccount mjBusinessAccount1 = businessAccountMapper.selectHasAddByBrandsNameToAddProject(req.getBrands(), req.getBusinessId());
            if (mjBusinessAccount1 != null) {
                project.setBrandId(mjBusinessAccount1.getId());
            } else {
                return new APPResultMessage(6004, "该商务下未找到该品牌");
            }
        }
        if (project.getBrandId() == null) {
            return new APPResultMessage(6004, "未找到该品牌");
        }
        if (StringUtil.isNotBlank(req.getBrandPlacement())) {
            project.setBrandPlacement(req.getBrandPlacement());
        }
        if (StringUtil.isNotBlank(req.getBrandPlacementPic())) {
            project.setBrandPlacementPic(req.getBrandPlacementPic());
        }
        // 添加项目经理与选品人的数据
        if (req.getBusinessId() == null) {
            return new APPResultMessage<>(6005, "未找到该商务");
        }
        MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(req.getBusinessId());
        if (businessPerson == null) {
            return new APPResultMessage<>(6006, "未找到该商务");
        }
        projectMapper.insert(project);
        MjProjectStage mjProjectStage = new MjProjectStage();
        mjProjectStage.setProjectId(project.getId());
        mjProjectStage.setCode(ProjectStatusEnum.CREATE.getCode());
        mjProjectStage.setName(ProjectStatusEnum.CREATE.getName());
        mjProjectStage.setIsCurrent(true);
        mjProjectStage.setStartTime(new Date());
        mjProjectStage.setSort(0);
        mjProjectStage.setCreateTime(new Date());
        projectStageMapper.insert(mjProjectStage);
        if (project.getBrandId() != null) {
            MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddById(project.getBrandId());
            if (mjBusinessAccount != null && mjBusinessAccount.getStatus() != 4) {
                mjBusinessAccount.setStatus((short) 2);
                businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
            }
        }

        String customValue = businessPerson.getCustomValue();
        if (StringUtil.isNotBlank(customValue)) {
            // {"product_selection_assistant":[117],"project_execution":null,"packaging_specialist":68,"contract_specialist":80,"product_selection_manager":130}
            JSONObject jsonObject = JSON.parseObject(customValue);
            List<ProjectUser> userList = new ArrayList<>();
            List<SysRole> sysRoles = roleMapper.selectCustomList();
            for (SysRole sysRole : sysRoles) {
                if (sysRole.getMultipleType() == 1) {
                    JSONArray jsonArray = jsonObject.getJSONArray(sysRole.getCustomName());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        Integer projectUserId = (Integer) jsonArray.get(i);
                        if (projectUserId != null) {
                            ProjectUser projectUser = new ProjectUser();
                            projectUser.setUserId(projectUserId);
                            projectUser.setUserType((short) 2);
                            projectUser.setRoleId(sysRole.getId());
                            projectUser.setStatus((short) 1);
                            projectUser.setCreateTime(new Date());
                            projectUser.setProjectId(project.getId());
                            userList.add(projectUser);
                        }
                    }
                } else {
                    Integer projectUserId = jsonObject.getInteger(sysRole.getCustomName());
                    if (projectUserId != null) {
                        ProjectUser projectUser = new ProjectUser();
                        projectUser.setUserId(projectUserId);
                        projectUser.setUserType((short) 2);
                        projectUser.setRoleId(sysRole.getId());
                        projectUser.setStatus((short) 1);
                        projectUser.setCreateTime(new Date());
                        projectUser.setProjectId(project.getId());
                        userList.add(projectUser);
                    }
                }
            }
            projectUserMapper.insertBatch(userList);
        }


        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(project.getId());
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage<Object, List> addMediaRequirementsOnly(MediaRequirementsBatchCreateReq req) {
        projectMediaRequirementsManageService.addProjectMediaRequirementsCreate(req);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(req.getProjectId());
        successMessage.setResult(resultMessage);
        return successMessage;
    }


//    public APPResultMessage<Object, List> addProjectIntendedOnly(MediaRequirementsCreateReq req) {
//
//        projectIntendedMediaManageService.doAddIntendedMedia(r);
//        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
//        ResultMessage resultMessage = ResultMessage.builder().setData(req.getProjectId());
//        successMessage.setResult(resultMessage);
//        return successMessage;
//    }


    public APPResultMessage<Object, List> addManageProject(ProjectEditReq req, Integer userId, Short userType) {
        MjProject project = new MjProject();
        project.setName(req.getName());
        project.setProjectName(req.getProjectName());
        project.setBrands(req.getBrands());
        project.setBrandsUsername(req.getBrandsUsername());
        project.setCateIds(req.getCateIds());
        project.setBussinessUsername(req.getBussinessUsername());
        project.setBusinessId(req.getBusinessId());
        project.setAreaId(req.getAreaId());
        project.setPermissionUsername(req.getPermissionUsername());
        project.setPermissionId(req.getPermissionId());
        project.setCreateTime(new Date());
        project.setStatus((short) 1);
        project.setProductName(req.getProductName());
        project.setProjectType(req.getProjectType());
        if (StringUtil.isNotBlank(req.getBrands())) {
            MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddByBrandsNameAndNoBrandId(req.getBrands(), req.getBusinessId());
            if (mjBusinessAccount != null) {
                return new APPResultMessage(6003, "该品牌处于受保状态，无法添加项目");
            }
            MjBusinessAccount mjBusinessAccount1 = businessAccountMapper.selectHasAddByBrandsNameToAddProject(req.getBrands(), req.getBusinessId());
            if (mjBusinessAccount1 != null) {
                project.setBrandId(mjBusinessAccount1.getId());
            } else {
                return new APPResultMessage(6004, "该商务下未找到该品牌");
            }
        }
        if (project.getBrandId() == null) {
            return new APPResultMessage(6004, "未找到该品牌");
        }
        if (StringUtil.isNotBlank(req.getBrandPlacement())) {
            project.setBrandPlacement(req.getBrandPlacement());
        }
        if (StringUtil.isNotBlank(req.getBrandPlacementPic())) {
            project.setBrandPlacementPic(req.getBrandPlacementPic());
        }
        // 添加项目经理与选品人的数据
        if (req.getBusinessId() == null) {
            return new APPResultMessage<>(6005, "未找到该商务");
        }
        MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(req.getBusinessId());
        if (businessPerson == null) {
            return new APPResultMessage<>(6006, "未找到该商务");
        }
        projectMapper.insert(project);
        if (project.getBrandId() != null) {
            MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddById(project.getBrandId());
            if (mjBusinessAccount != null && mjBusinessAccount.getStatus() != 4) {
                mjBusinessAccount.setStatus((short) 2);
                businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
            }
        }
        // 添加报备媒体
        if (StringUtil.isNotBlank(req.getMediumIds())) {
            String[] mediumIds = req.getMediumIds().split(",");
            projectIntendedMediaManageService.doAddIntendedMedia(mediumIds, project.getId(), true);
        }
        // 添加媒体需求
        if (req.getMediaRequirementsCreateReq() != null && StringUtil.isNotBlank(req.getMediaRequirementsCreateReq().getBrandPlacement())) {
            req.getMediaRequirementsCreateReq().setProjectId(project.getId());
            projectMediaRequirementsManageService.doAddProjectMediaRequirements(req.getMediaRequirementsCreateReq());
        }
        // 添加进程
        processManageService.doAddProcess(project.getId(), userId, userType, ProcessEnum.createProject, null);
        // 添加项目相关的用户id---商务
        ProjectUser projectBusinessUser = new ProjectUser();
        projectBusinessUser.setUserId(req.getBusinessId());
        projectBusinessUser.setUserType((short) 3);
        projectBusinessUser.setRoleId(40);
        projectBusinessUser.setStatus((short) 1);
        projectBusinessUser.setCreateTime(new Date());
        projectBusinessUser.setProjectId(project.getId());
        projectUserMapper.insertSelective(projectBusinessUser);

        // 添加项目相关的用户id
        String customValue = businessPerson.getCustomValue();
        if (StringUtil.isNotBlank(customValue)) {
            // {"product_selection_assistant":[117],"project_execution":null,"packaging_specialist":68,"contract_specialist":80,"product_selection_manager":130}
            JSONObject jsonObject = JSON.parseObject(customValue);
            List<ProjectUser> userList = new ArrayList<>();
            List<SysRole> sysRoles = roleMapper.selectCustomList();
            for (SysRole sysRole : sysRoles) {
                if (sysRole.getMultipleType() == 1) {
                    JSONArray jsonArray = jsonObject.getJSONArray(sysRole.getCustomName());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        Integer projectUserId = (Integer) jsonArray.get(i);
                        if (projectUserId != null) {
                            ProjectUser projectUser = new ProjectUser();
                            projectUser.setUserId(projectUserId);
                            projectUser.setUserType((short) 2);
                            projectUser.setRoleId(sysRole.getId());
                            projectUser.setStatus((short) 1);
                            projectUser.setCreateTime(new Date());
                            projectUser.setProjectId(project.getId());
                            userList.add(projectUser);
                        }
                    }
                } else {
                    Integer projectUserId = jsonObject.getInteger(sysRole.getCustomName());
                    if (projectUserId != null) {
                        ProjectUser projectUser = new ProjectUser();
                        projectUser.setUserId(projectUserId);
                        projectUser.setUserType((short) 2);
                        projectUser.setRoleId(sysRole.getId());
                        projectUser.setStatus((short) 1);
                        projectUser.setCreateTime(new Date());
                        projectUser.setProjectId(project.getId());
                        userList.add(projectUser);
                    }
                }
            }
            projectUserMapper.insertBatch(userList);
        }

        Map<String, Object> templateParams = new HashMap<>();
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(project.getId());
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage<Object, List> delManageProject(ProjectIdReq req, int userId, Short userType) {
        projectMapper.updateStatusById(req.getProjectId(), (short) 10);
        orderMapper.updateStatusByProjectId(req.getProjectId(), (short) 10);
        //记录操作日志
        logOperateMapper.addSelective(req.getProjectId(), null, userId, 216, new Date(), 3);
        // 添加进程，不进行通知
//        processManageService.doAddProcess(req.getProjectId(), userId, userType, ProcessEnum.delProject, null);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage<ProjectListDTO, List> getProjectManageMsg(ProjectIdReq req) {
        //该项目的总到货百分比
        BigDecimal arrivalRateSum = BigDecimal.ZERO;
        ProjectListDTO dto = projectMapper.selectMsgById(req.getProjectId());
        List<MjProjectBatch> batchList = projectBatchMapper.selectBatchByProjectId(dto.getId());
        //设置批次列表
        if (CollUtil.isNotEmpty(batchList)) {
            dto.setProjectBatchListbatchList(batchList);
            for (MjProjectBatch mjProjectBatch : batchList) {
                //计算到货百分比
                if (mjProjectBatch.getArrivalRate() != null) {
                    arrivalRateSum = arrivalRateSum.add(mjProjectBatch.getArrivalRate());
                }
            }
        }
        dto.setArrivalRate(arrivalRateSum);

        //最后到货时间
        MjProjectBatch mjProjectBatch = projectBatchMapper.selectProjectBatchMaxTime(req.getProjectId());
        if (mjProjectBatch != null && mjProjectBatch.getArrivalTime() != null) {
            dto.setArrivalTime(mjProjectBatch.getArrivalTime());
        }

        if (StringUtil.isNotBlank(dto.getAreaId())) {
            String areaIds = dto.getAreaId();
            String areaName = "";
            for (String areaId : areaIds.split(",")) {
                SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(areaId));
                areaName = areaName + labelValue.getSysValueName() + ";";
            }
            dto.setAreas(areaName);
        }
        if (StringUtil.isNotBlank(dto.getCateIds())) {
            String cateIds = dto.getCateIds();
            String name = "";
            for (String id : cateIds.split(",")) {
                SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                name = name + labelValue.getSysValueName() + ";";
            }
            dto.setCates(name);
        }
        List<MjOrder> orders = orderMapper.selectListByProjectId(dto.getId());
        for (MjOrder order : orders) {
            // 项目货值
            dto.setProjectTotalPrice(dto.getProjectTotalPrice().add(order.getTotalPrice() == null ? BigDecimal.ZERO : order.getTotalPrice()));
            // 内部货值 = 到货百分比 * 订单总内部货值
            dto.setInnerTotalPrice(dto.getInnerTotalPrice().add(order.getInnerPrice() == null ? BigDecimal.ZERO : order.getInnerPrice()));
            // 预估成本
            dto.setEstimatedCost(dto.getEstimatedCost().add(order.getEstimatedCost() == null ? BigDecimal.ZERO : order.getEstimatedCost()));
            // 实际成本
            dto.setActualCost(dto.getActualCost().add(order.getActualCost() == null ? BigDecimal.ZERO : order.getActualCost()));
            // 盲盒应收
            dto.setBlindPrice(dto.getBlindPrice().add(order.getBlindBoxPrice() == null ? BigDecimal.ZERO : order.getBlindBoxPrice()));
            // 盲盒实收
            dto.setBlindRealPrice(dto.getBlindRealPrice().add(order.getBlindRealPrice() == null ? BigDecimal.ZERO : order.getBlindRealPrice()));
            // 卖货应收
            dto.setSalePrice(dto.getSalePrice().add(order.getCheckCashPrice() == null ? BigDecimal.ZERO : order.getCheckCashPrice()));
            // 卖货实收
            dto.setSaleRealPrice(dto.getSaleRealPrice().add(order.getSaleRealPrice() == null ? BigDecimal.ZERO : order.getSaleRealPrice()));
        }
        //到货货值 : 到货百分比*内部货值
        dto.setArrivalInnerPrice(dto.getInnerTotalPrice() == null ? BigDecimal.ZERO :
                dto.getInnerTotalPrice().multiply(arrivalRateSum).multiply(BigDecimal.valueOf(0.01)));

        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(dto);
        successMessage.setResult(resultMessage);
        return successMessage;
    }


    public APPResultMessage editManageProjectContract(ProjectEditReq req) {
        projectMapper.updateContractUrlById(req.getId(), req.getContractUrl());
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage editManageArrivalProgress(ProjectEditReq req) {
        if (null != req.getExecutionProgressId() || null != req.getArrivalProgressId() || null != req.getArrivalWarehouseId()) {
            MjProject project = new MjProject();
            project.setId(req.getId());
            project.setExecutionProgressId(req.getExecutionProgressId());
            project.setArrivalProgressId(req.getArrivalProgressId());
            project.setArrivalWarehouseId(req.getArrivalWarehouseId());
            projectMapper.updateByPrimaryKeySelective(project);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage editManageActualValuePrice(ProjectEditReq req) {
        projectMapper.updateActualValuePriceById(req.getId(), req.getActualValuePrice());
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage editManageDiscount(ProjectEditReq req) {
        projectMapper.updateDiscountById(req.getId(), req.getIsDiscount(), req.getDiscountContent(), req.getDiscountPic());
        return APPResultMessage.getSuccessMessage();
    }

    @Transactional
    public APPResultMessage doSureCheckProject(int projectId, Date chooseDate, Integer userId, String productName,
                                               String invoiceCompany,
                                               BigDecimal invoicePrice,
                                               String orderNo) {

        MjProjectStage stage = projectStageMapper.selectOne(
                new LambdaQueryWrapper<MjProjectStage>()
                        .eq(MjProjectStage::getProjectId, projectId)
                        .eq(MjProjectStage::getIsCurrent, 1)
        );
        if (!stage.getCode().equals(ProjectStatusEnum.SIGNED.getName())) {
            MjProjectStage mjProjectStage = new MjProjectStage();


            mjProjectStage.setProjectId(projectId);
            mjProjectStage.setIsCurrent(true);
            mjProjectStage.setName(ProjectStatusEnum.SIGNED.getName());
            mjProjectStage.setCode(ProjectStatusEnum.SIGNED.getCode());
            mjProjectStage.setSort(stage.getSort() + 1);
            mjProjectStage.setCreateTime(new Date());

            stage.setIsCurrent(false);
            stage.setEndTime(new Date());

            projectStageMapper.insert(mjProjectStage);
            projectStageMapper.updateById(stage);
        }
        List<MjOrder> orders = orderMapper.selectSureListByProjectId(projectId);
        if (BeanUtil.isNullList(orders)) {
            return new APPResultMessage(5001, "无订单可确认签单");
        }
        Boolean hasAllCheckOrder = true;
        Boolean hasCheckOrder = false; // 判断是否是已签单的状态
        Boolean hasBlindOrder = false; // 判断是否是盲盒
        String orderIds = "";
        for (int i = 0; i < orders.size(); i++) {
            MjOrder order = orders.get(i);
            if (order.getStatus() != 3) {
                hasAllCheckOrder = false;
            }
            if (order.getCheckTime() != null) {
                hasCheckOrder = true;
            }
            if (order.getIsBlindBox() != null && order.getIsBlindBox() == 2) {
                hasBlindOrder = true;
            }
            orderIds = orderIds + order.getId() + (i < (orders.size() - 1) ? "," : "");
        }
        if (hasCheckOrder) {
            return new APPResultMessage(6001, "已确认签单");
        }
        if (!hasAllCheckOrder && !hasBlindOrder) {
            return new APPResultMessage(5002, "请确认订单是否处于等待签单的状态");
        }
        for (MjOrder order : orders) {
            if (order.getStatus() == 3) {
                Set<Integer> allPushUserId = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(), order.getBiddingPushUserIds());
                //项目的订单的所有开拓者显示已签单状态
                for (Integer pushUserId : allPushUserId) {
                    MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
                    orderStatusObj2.setOrderStatus(85);
                    orderStatusObj2.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, order.getId());
                    if (isHaveObj2 != null) {
                        orderStatusObj2.setId(isHaveObj2.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
                    }
                }
            }
        }
        MjProject mjProject = projectMapper.selectByPrimaryKey(projectId);
        mjProject.setCheckTime(chooseDate);
        mjProject.setProjectName(productName);
        mjProject.setInvoiceCompany(invoiceCompany);
        mjProject.setInvoicePrice(invoicePrice);
        projectMapper.updateById(mjProject);
        MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddById(mjProject.getBrandId());
        if (mjBusinessAccount != null && mjBusinessAccount.getStatus() != 4) {
            mjBusinessAccount.setStatus((short) 4);
            mjBusinessAccount.setBeginTime(new Date());
            String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(37);
            Date endTime = DateUtil.getChooseDate(new Date(), 2, Integer.valueOf(sysValue));
            mjBusinessAccount.setEndTime(endTime);
            businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
        }
        String[] split = orderIds.split(",");
        for (String id : split) {
            // 更新订单状态，如果是盲盒的话，状态直接是已完成
            MjOrder mjOrder = orderMapper.selectByPrimaryKey(Integer.valueOf(id));
            if (mjOrder.getIsBlindBox() != null && mjOrder.getIsBlindBox() == 2) {
                orderMapper.updateCheckStatusByOrderIds(split, (short) 7);
                orderMapper.updateEndTime(Integer.valueOf(id), new Date());
                projectMapper.updateStatusById(projectId, (short) 4);
                //所有开拓者为已结束
                Set<Integer> allPushUserId = getAllPushUserIds(mjOrder.getPushUserIds(), mjOrder.getNextPushUserIds(), mjOrder.getTransferUserIds(), mjOrder.getBiddingPushUserIds());
                for (Integer pushUserId : allPushUserId) {
                    MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
                    orderStatusObj2.setOrderStatus(88);
                    orderStatusObj2.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, mjOrder.getId());
                    if (isHaveObj2 != null) {
                        orderStatusObj2.setId(isHaveObj2.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
                    }
                }
            } else {
                orderMapper.updateCheckStatusByOrderIds(split, (short) 4);
                projectMapper.updateStatusById(projectId, (short) 4);
            }


        }

        //记录操作日志
        logOperateMapper.addSelective(projectId, null, userId, 204, new Date(), 3);
        // TODO: 2023/8/31 0031 推送给发布者初次确定的开拓者，让开拓者确定一次竞价的结束时间
        for (String id : split) {
//            RedisUtil.setCacheObject("readOrder_" + id, GlobalStatic.noRead2);
            MjOrder order = orderMapper.selectByPrimaryKey(Integer.valueOf(id));
            String pushUserIds = order.getPushUserIds();
            sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "已确认核价-确定第一次竞价的结束时间", "该项目订单已确认核价，请确定第一次竞价的结束时间", null);
        }

        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doFailManageProject(int projectId, String failReason) {
        projectMapper.updateFailStatusByProjectId(projectId, failReason);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doPackageManageProject(int userId, int projectId, String mediums, Integer chooseAddIndex) {
        Integer addIndex = 1;
        Short status = 1;
        Map<String, Date> chooseTimeMap = new HashMap();
        Map<String, Date> chooseEndTimeMap = new HashMap();
        if (chooseAddIndex == null) {
            MjProjectMedium medium = projectMediumMapper.selectLastAddIndexByProjectId(projectId);
            if (medium == null) {
                addIndex = 1;
            } else {
                addIndex = (medium.getAddIndex() == null ? 1 : medium.getAddIndex()) + 1;
            }
        } else {
            List<MjProjectMedium> projectMedium = projectMediumMapper.selectListMsgByAddIndexAndUserIdAndProjectId(chooseAddIndex, projectId);
            if (!BeanUtil.isNullList(projectMedium)) {
                status = projectMedium.get(0).getStatus();
                int index = 0;
                for (MjProjectMedium medium : projectMedium) {
                    chooseTimeMap.put(medium.getLineId() + "-" + index, medium.getChooseTime());
                    chooseEndTimeMap.put(medium.getLineId() + "-" + index, medium.getChooseEndTime());
                    index++;
                }
                projectMediumMapper.updateStatusByAddIndexAndUserId(chooseAddIndex, projectId);
                mediumOtherProjectManageService.doAddMediumOtherProjectUpdate(projectMedium.get(0).getId(), userId);
            }
            addIndex = chooseAddIndex;
        }
        List<ProjectMediumDTO> dtos = JSON.parseArray(mediums, ProjectMediumDTO.class);
        for (ProjectMediumDTO dto : dtos) {
            MjProjectMedium projectMedium = new MjProjectMedium();
            projectMedium.setProjectId(projectId);
            projectMedium.setLineType(dto.getMediumType());
            projectMedium.setLineId(dto.getMediumId());
            projectMedium.setStatus(status);
            projectMedium.setUserId(userId);
            projectMedium.setUpdateTime(new Date());
            projectMedium.setCreateTime(new Date());
            projectMedium.setNum(dto.getNum());
            projectMedium.setNum2(dto.getNum2());
            projectMedium.setAddIndex(addIndex);
            if (dto.getMediumType() == 1) {
                MjMediumOnline mediumOnline = mediumOnlineMapper.selectByPrimaryKey(dto.getMediumId());
                projectMedium.setTotalPrice((mediumOnline != null && mediumOnline.getGoodPrice() != null ? (mediumOnline.getGoodPrice().multiply(new BigDecimal(dto.getNum()))) : BigDecimal.ZERO));
                projectMedium.setCost(mediumOnline.getCost());
                projectMedium.setGoodPrice(mediumOnline.getGoodPrice());
                projectMediumMapper.insertSelective(projectMedium);
                mediumOtherProjectManageService.doAddMediumOtherProjectUpdate(projectMedium.getId(), userId);
            } else if (dto.getMediumType() == 2) {
                MjMediumOffline mjMediumOffline = mediumOfflineMapper.selectByPrimaryKey(dto.getMediumId());
                projectMedium.setCost(mjMediumOffline.getCost());
                projectMedium.setGoodPrice(mjMediumOffline.getGoodPrice());
                projectMedium.setTotalPrice((mjMediumOffline != null && mjMediumOffline.getGoodPrice() != null ? (mjMediumOffline.getGoodPrice()) : BigDecimal.ZERO));
                String putInCycleTypeName = "周";
                if (dto.getNum() > 0) {
                    int putInCycleNum = 1;
                    if (StringUtil.isNotBlank(mjMediumOffline.getPutInCycle())) {
                        if (mjMediumOffline.getPutInCycle().contains("月")) {
                            putInCycleTypeName = "月";
                            putInCycleNum = Integer.valueOf(mjMediumOffline.getPutInCycle().substring(0, mjMediumOffline.getPutInCycle().indexOf("月")));
                        } else if (mjMediumOffline.getPutInCycle().contains("周")) {
                            putInCycleTypeName = "周";
                            putInCycleNum = Integer.valueOf(mjMediumOffline.getPutInCycle().substring(0, mjMediumOffline.getPutInCycle().indexOf("周")));
                        }
                    }
                    for (int i = 0; i < dto.getNum(); i++) {
                        if (chooseTimeMap.get(dto.getMediumId() + "-" + i) != null) {
                            projectMedium.setChooseTime(chooseTimeMap.get(dto.getMediumId() + "-" + i));
                        }
                        if (chooseEndTimeMap.get(dto.getMediumId() + "-" + i) != null) {
                            projectMedium.setChooseEndTime(chooseEndTimeMap.get(dto.getMediumId() + "-" + i));
                        }
                        projectMedium.setNum(putInCycleNum);
                        projectMedium.setNumTypeName(putInCycleTypeName);
                        projectMediumMapper.insertSelective(projectMedium);
                        mediumOtherProjectManageService.doAddMediumOtherProjectUpdate(projectMedium.getId(), userId);
                    }
                }
            }
        }
        projectMapper.updateIsPackageById(projectId);
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage viewPackageManageProjectList(int projectId) {
        List<MediumPackageList> lists = projectMediumMapper.selectPackageListByProjectId(projectId);
        for (MediumPackageList list : lists) {
            List<MjProjectMedium> dtoList = projectMediumMapper.selectMediumListByProjectIdAndAddIndex(projectId, list.getAddIndex());
            List<Map> mediumList = new ArrayList<>();
            BigDecimal cost = BigDecimal.ZERO;
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (MjProjectMedium medium : dtoList) {
                Map map = new HashMap();
                map.put("id", medium.getId());
                map.put("lineType", medium.getLineType());
                map.put("lineId", medium.getLineId());
                map.put("projectId", medium.getProjectId());
                map.put("num", medium.getNum());
                map.put("num2", medium.getNum2());
                map.put("numTypeName", medium.getNumTypeName());
                map.put("totalPrice", medium.getTotalPrice());
                map.put("chooseTime", medium.getChooseTime());
                map.put("chooseEndTime", medium.getChooseEndTime());
                String mediumName = "";
                if (medium.getLineType() == 1) {
                    MediumOnlineDTO mediumOnline = mediumOnlineMapper.selectManageMsg(medium.getLineId());
                    mediumName = mediumOnline.getPlateName();
                } else if (medium.getLineType() == 2) {
                    MediumOfflineDTO mjMediumOffline = mediumOfflineMapper.selectManageMsg(medium.getLineId());
                    mediumName = mjMediumOffline.getName();
                    map.put("putInCycle", mjMediumOffline.getPutInCycle());
                }
                map.put("mediumName", mediumName);
                map.put("cost", medium.getCost());
                mediumList.add(map);
                if (medium.getCost() != null && medium.getNum2() != null) {
                    Integer num = 1;
                    if (medium.getLineType() == 1) {
                        num = medium.getNum();
                    }
                    BigDecimal multiply = medium.getCost().multiply(new BigDecimal(medium.getNum2())).multiply(new BigDecimal(num));
                    cost = cost.add(multiply);
                }
                if (medium.getTotalPrice() != null && medium.getNum2() != null) {
                    Integer num = 1;
                    if (medium.getLineType() == 1) {
                        num = medium.getNum();
                    }
                    BigDecimal multiply = medium.getTotalPrice().multiply(new BigDecimal(medium.getNum2())).multiply(new BigDecimal(num));
                    totalPrice = totalPrice.add(multiply);
                }
            }
            list.setMediumList(mediumList);
            list.setTotalPrice(totalPrice);
            list.setCost(cost);
        }
        ResultMessage resultMessage = ResultMessage.builder().setList(lists);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage viewPackageManageProjectMsg(int projectId, int indexNum) {
        List<ProjectMediumListDTO> dtos = projectMediumMapper.selectListByProjectIdAndIndexNum(projectId, indexNum);
        for (ProjectMediumListDTO dto : dtos) {
            if (dto.getLineType() == 1) {
                MediumOnlineDTO mediumOnline = mediumOnlineMapper.selectManageMsg(dto.getLineId());
                dto.setMediumOnline(mediumOnline);
            } else if (dto.getLineType() == 2) {
                MediumOfflineDTO mjMediumOffline = mediumOfflineMapper.selectManageMsg(dto.getLineId());
                dto.setMediumOffline(mjMediumOffline);
                dto.setOfflineMediumType(mjMediumOffline.getOfflineType());
            }
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(dtos);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage viewPackageManageProjectExportMsg(int projectId, int indexNum) {
        List<ProjectMediumListDTO> list = new ArrayList<>();
        List<ProjectMediumListDTO> dtos = projectMediumMapper.selectExportListByProjectIdAndIndexNum(projectId, indexNum);
        for (ProjectMediumListDTO dto : dtos) {
            if (dto.getLineType() == 1) {
                MediumOnlineDTO mediumOnline = mediumOnlineMapper.selectManageMsg(dto.getLineId());
                dto.setMediumOnline(mediumOnline);
            } else if (dto.getLineType() == 2) {
                MediumOfflineDTO mjMediumOffline = mediumOfflineMapper.selectManageMsg(dto.getLineId());
                dto.setMediumOffline(mjMediumOffline);
                dto.setOfflineMediumType(mjMediumOffline.getOfflineType());
            }
            if (!BeanUtil.isNullList(list)) {
                if (!hasSetList(list, dto)) {
                    list.add(dto);
                }
            } else {
                list.add(dto);
            }
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(list);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public static boolean hasSetList(List<ProjectMediumListDTO> list, ProjectMediumListDTO dto) {
        boolean hasSet = false;
        for (ProjectMediumListDTO projectMediumListDTO : list) {
            if (projectMediumListDTO.getLineType() == dto.getLineType()
                    && projectMediumListDTO.getLineId() == dto.getLineId()) {
                hasSet = true;
            }
        }
        return hasSet;
    }

    public APPResultMessage viewOfflineHasPackageProjectList(Date startDate, Date endDate, Integer projectId,
                                                             Integer addIndex, Integer chooseProjectId,
                                                             String chooseYihuoProjectIds, Integer showChooseProjectType,
                                                             String chooseMediumOtherProjectIds, String roleIds) {
        if (startDate == null || endDate == null) {
            return APPResultMessage.getErrorMessage("开始时间或结束时间不能为空");
        } else {
            boolean isBusiness = false;
            // 判断是否是商务账户
            if (StringUtil.isNotBlank(roleIds) && (StringUtil.containsString(roleIds.split(","), "40") || StringUtil.containsString(roleIds.split(","), "55"))) {
                isBusiness = true;
            }
            String[] chooseYihuoProjectIdList = null;
            if (StringUtil.isNotBlank(chooseYihuoProjectIds)) {
                chooseYihuoProjectIdList = chooseYihuoProjectIds.split(",");
            }
            String[] chooseMediumOtherProjectIdList = null;
            if (StringUtil.isNotBlank(chooseMediumOtherProjectIds)) {
                chooseMediumOtherProjectIdList = chooseMediumOtherProjectIds.split(",");
            }
            // 如果存在查询项目的情况下，只展示对应的媒体
            List<Integer> mediumIdList = new ArrayList<>();
            if (chooseYihuoProjectIdList != null && chooseYihuoProjectIdList.length > 0) {
                List<Integer> mediumIds = projectMediumMapper.selectMediumIdListByLineTypeAndProjectIds(2, chooseYihuoProjectIdList);
                mediumIdList.addAll(mediumIds);
            }
            if (chooseMediumOtherProjectIdList != null && chooseMediumOtherProjectIdList.length > 0) {
                List<Integer> mediumIds = projectMediumMapper.selectMediumIdListByLineTypeAndProjectIds(3, chooseMediumOtherProjectIdList);
                mediumIdList.addAll(mediumIds);
            }
            List<MediumAllProjectDTO> lists = mediumOfflineMapper.selectAllOfflineListByProjectId(projectId, addIndex, chooseProjectId,
                    chooseYihuoProjectIdList, null, chooseMediumOtherProjectIdList, mediumIdList);
            for (MediumAllProjectDTO dto : lists) {
                Date chooseStartDate = startDate;
                Date chooseEndDate = endDate;
//                if (StringUtil.isNotBlank(dto.getPutInCycle())){
//                    if (dto.getPutInCycle().contains("月")){
//                        chooseStartDate = DateUtil.getChooseDate(chooseStartDate, 2, -1);
//                        chooseEndDate = DateUtil.getChooseDate(chooseEndDate, 2, 1);
//                    } else {
//                        chooseStartDate = DateUtil.getChooseDate(chooseStartDate, 1, -6);
//                        chooseEndDate = DateUtil.getChooseDate(chooseEndDate, 1, 6);
//                    }
//                }
                List<MediumProjectMsgDTO> projectLists = mediumOfflineMapper.selectOfflineHasPackageProjectList(chooseStartDate, chooseEndDate, dto.getId(), projectId, addIndex,
                        chooseYihuoProjectIdList, showChooseProjectType, chooseMediumOtherProjectIdList, isBusiness);
                if (!BeanUtil.isNullList(projectLists)) {
                    dto.setProjectMsgDTOList(projectLists);
                }
            }
            ResultMessage resultMessage = ResultMessage.builder().setList(lists);
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage doDelProjectPackage(int projectId, int indexNum, Integer userId) {
        MjProjectMedium projectMedium = projectMediumMapper.selectOneMsgByAddIndexAndUserIdAndProjectId(indexNum, projectId);
        if (projectMedium != null && projectMedium.getStatus() == 2) {
            return APPResultMessage.getErrorMessage("该项目不允许被删除");
        }
        projectMediumMapper.updateStatusByAddIndexAndUserId(indexNum, projectId);
        if (projectMedium != null) {
            mediumOtherProjectManageService.doAddMediumOtherProjectUpdate(projectMedium.getId(), userId);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doCheckDateByPackageAndLineIndexAndAreaType(int lineId, Integer chooseId, Date chooseDate, Integer endDayNum, Integer lineIndex, Integer areaType) {
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        MjMediumOffline mediumOffline = mediumOfflineMapper.selectByPrimaryKey(lineId);
        if (StringUtil.isBlank(mediumOffline.getPutInCycle())) {
            return new APPResultMessage(6001, "该媒体未设置投放周期，请设置后进行排期");
        }
        Integer dayType = 1; // 1、周，2、月
        Integer dayNum = 1; //周数或者月数
        if (StringUtil.isNotBlank(mediumOffline.getPutInCycle())) {
            if (mediumOffline.getPutInCycle().contains("月")) {
                dayType = 2;
                dayNum = Integer.valueOf(mediumOffline.getPutInCycle().substring(0, mediumOffline.getPutInCycle().indexOf("月")));
            } else if (mediumOffline.getPutInCycle().contains("周")) {
                dayType = 1;
                dayNum = Integer.valueOf(mediumOffline.getPutInCycle().substring(0, mediumOffline.getPutInCycle().indexOf("周")));
            }
        }
        Date chooseEndDate = null;
        if (chooseDate != null) {
            chooseEndDate = DateUtil.getChooseEndDate(chooseDate, dayNum, dayType);
            if (endDayNum != null) {
                chooseEndDate = DateUtil.getEndDate(chooseDate, endDayNum, 1);
            }
            MjProjectMedium projectMedium = projectMediumMapper.getCheckListHasLimitNumByChooseDateAndIndexAndAreaType(chooseDate, chooseEndDate, lineId, chooseId, lineIndex, areaType);
            if (projectMedium != null) {
                return new APPResultMessage(6002, "该时间段已被占满，请选择其他时间");
            }
        }
        return successMessage;
    }

    public APPResultMessage doCheckDateByPackage(int lineId, Integer chooseId, Date chooseDate, Integer endDayNum, Integer lineIndex, Integer areaType) {
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        MjMediumOffline mediumOffline = mediumOfflineMapper.selectByPrimaryKey(lineId);
        if (StringUtil.isBlank(mediumOffline.getPutInCycle())) {
            return new APPResultMessage(6001, "该媒体未设置投放周期，请设置后进行排期");
        }
        Integer dayType = 1; // 1、周，2、月
        Integer dayNum = 1; //周数或者月数
        if (StringUtil.isNotBlank(mediumOffline.getPutInCycle())) {
            if (mediumOffline.getPutInCycle().contains("月")) {
                dayType = 2;
                dayNum = Integer.valueOf(mediumOffline.getPutInCycle().substring(0, mediumOffline.getPutInCycle().indexOf("月")));
            } else if (mediumOffline.getPutInCycle().contains("周")) {
                dayType = 1;
                dayNum = Integer.valueOf(mediumOffline.getPutInCycle().substring(0, mediumOffline.getPutInCycle().indexOf("周")));
            }
        }
        Date chooseEndDate = null;
        if (chooseDate != null) {
            chooseEndDate = DateUtil.getChooseEndDate(chooseDate, dayNum, dayType);
            if (endDayNum != null) {
                chooseEndDate = DateUtil.getEndDate(chooseDate, endDayNum, 1);
            }
//            List<Date> dateList = DateUtil.getDateListByStartTimeAndEndTime(chooseDate, chooseEndDate);
            List<MjProjectMedium> checkListHasLimitNumByChooseDate = projectMediumMapper.getCheckListHasLimitNumByChooseDate(chooseDate, chooseEndDate, lineId, chooseId, lineIndex, areaType);
            Boolean isLimitStatus = false;
            if (!BeanUtil.isNullList(checkListHasLimitNumByChooseDate)) {
                isLimitStatus = true; // 有数据说明已经被占用了
                // 判断这个时间内是否已经被占满
//                for (Date date : dateList){
//                    Integer dateNum = 0; //每天的数量
//                    for (MjProjectMedium medium : checkListHasLimitNumByChooseDate){
//                        if (medium != null){
//                            if (Long.valueOf(DateUtil.getyyyyMMdd(date)) >= Long.valueOf(DateUtil.getyyyyMMdd(medium.getChooseTime()))
//                                    && Long.valueOf(DateUtil.getyyyyMMdd(date)) <= Long.valueOf(DateUtil.getyyyyMMdd(medium.getChooseEndTime()))){
//                                if (medium.getId() != chooseId){
//                                    dateNum++;
//                                }
//                            }
//                        }
//                    }
//                    if (dateNum >= mediumOffline.getNum()){
//                        isLimitStatus = true;
//                        break;
//                    }
//                }
            }
            if (isLimitStatus) {
                return new APPResultMessage(6002, "该时间段已被占用，请选择其他时间");
            }
        }
        return successMessage;
    }

    public APPResultMessage doSetProjectPackageTime(int projectId, int lineId, Integer chooseId, Date chooseDate, Integer addIndex,
                                                    Integer userId, Integer endDayNum, Integer lineIndex, Integer areaType) {
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        try {
            APPResultMessage appResultMessage = doCheckDateByPackage(lineId, chooseId, chooseDate, endDayNum, lineIndex, areaType);
            if (appResultMessage.getKey() != 1000) {
                return appResultMessage;
            }
            MjMediumOffline mediumOffline = mediumOfflineMapper.selectByPrimaryKey(lineId);
            Integer dayType = 1; // 1、周，2、月
            Integer dayNum = 1; //周数或者月数
            if (StringUtil.isNotBlank(mediumOffline.getPutInCycle())) {
                if (mediumOffline.getPutInCycle().contains("月")) {
                    dayType = 2;
                    dayNum = Integer.valueOf(mediumOffline.getPutInCycle().substring(0, mediumOffline.getPutInCycle().indexOf("月")));
                } else if (mediumOffline.getPutInCycle().contains("周")) {
                    dayType = 1;
                    dayNum = Integer.valueOf(mediumOffline.getPutInCycle().substring(0, mediumOffline.getPutInCycle().indexOf("周")));
                }
            }
            Date chooseEndDate = null;
            if (chooseDate != null) {
                chooseEndDate = DateUtil.getChooseEndDate(chooseDate, dayNum, dayType);
                if (endDayNum != null) {
                    // 如果前端传了结束的天数，结束时间用这个
                    chooseEndDate = DateUtil.getEndDate(chooseDate, endDayNum, 1);
                }
            }
            if (chooseId == null) {
                // 表示是新增的时间，需要按顺序排
                MjProjectMedium projectMedium = projectMediumMapper.selectNoChooseTimeByAddIndexAndProjectIdAndLineId(addIndex, projectId, lineId);
                if (projectMedium != null) {
                    projectMedium.setChooseTime(chooseDate);
                    projectMedium.setChooseEndTime(chooseEndDate);
                    projectMedium.setUpdateTime(new Date());
                    projectMedium.setLineIndex(lineIndex);
                    projectMedium.setAreaType(areaType);
                    projectMediumMapper.updateByPrimaryKeySelective(projectMedium);
                    mediumOtherProjectManageService.doAddMediumOtherProjectUpdate(projectMedium.getId(), userId);
                }
            } else {
                // 表示是已设置过时间的
                projectMediumMapper.updateChooseTimeById(chooseId, chooseDate, chooseEndDate, lineIndex, areaType);
                mediumOtherProjectManageService.doAddMediumOtherProjectUpdate(chooseId, userId);
            }
            return successMessage;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            return successMessage;
        }
    }

    public APPResultMessage doSureProjectPackage(int projectId, int indexNum) {
        MjProjectMedium projectMedium = projectMediumMapper.selectHasJoinByProjectId(projectId);
        if (projectMedium != null) {
            return APPResultMessage.getErrorMessage("该项目已确认过配包");
        }
        projectMediumMapper.updateChooseStatusByAddIndexAndProjectId(indexNum, projectId);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doGetHasAddProjectName(String name, Integer projectId) {
        Integer getHas = 1; // 判断有无数据，1、无数据，2、有数据
        MjProject project = projectMapper.selectMsgByName(name, projectId);
        if (project != null) {
            getHas = 2;
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(getHas);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage doSureFinalProject(int projectId, Date date) {
        projectMapper.updateFinalTimeByProjectId(projectId, date);

        MjProject mjProject = projectMapper.selectByPrimaryKey(projectId);
        MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddById(mjProject.getBrandId());
        if (mjBusinessAccount != null && mjBusinessAccount.getStatus() != 4) {
            mjBusinessAccount.setOrderTime(new Date());
            mjBusinessAccount.setStatus((short) 4);
            mjBusinessAccount.setBeginTime(new Date());
            String sysValue = sysLabelValueMapper.selectValueBySysIdAndReadOne(38);
            Date endTime = DateUtil.getChooseDate(new Date(), 2, Integer.valueOf(sysValue));
            mjBusinessAccount.setEndTime(endTime);
            businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage editProjectCheckTime(int projectId, Date targetCheckTime, Integer userId) {
        MjProject project = new MjProject();
        project.setId(projectId);
        project.setCheckTime(targetCheckTime);
        projectMapper.updateByPrimaryKeySelective(project);
        //记录操作日志
        logOperateMapper.addSelective(projectId, null, userId, 205, new Date(), 3);
        return APPResultMessage.getSuccessMessage();
    }

    public Set<Integer> getAllPushUserIds(String pushUserIds, String nextPushUserIds, String transferUserIds, String biddingPushUserIds) {
        Set<Integer> userIdSet = new HashSet<>();
        if (StringUtil.isNotBlank(pushUserIds)) {
            List<Integer> str1 = Arrays.stream(pushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str1);
        }

        if (StringUtil.isNotBlank(nextPushUserIds)) {
            List<Integer> str2 = Arrays.stream(nextPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str2);
        }
        if (StringUtil.isNotBlank(transferUserIds)) {
            List<Integer> str3 = Arrays.stream(transferUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str3);
        }
        if (StringUtil.isNotBlank(biddingPushUserIds)) {
            List<Integer> str4 = Arrays.stream(biddingPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str4);
        }
        return userIdSet;
    }

    public APPResultMessage getOneProjectPackageList(int projectId, Short lineType) {
        List<ProjectMediumAllList> projectMediumListDTOS = projectMediumMapper.selectListByProjectIdAndLineType(projectId, lineType);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(projectMediumListDTOS);
        successMessage.setResult(resultMessage);
        return successMessage;
    }

    public APPResultMessage doAddIntendedMedia(ProjectAddIntendedMediaReq req) {
        if (StringUtil.isBlank(req.getMediumIds())) {
            return new APPResultMessage(6001, "请选择报备媒体");
        }
        if (req.getProjectId() == null) {
            return new APPResultMessage(6001, "请选择项目");
        }
        MjProject project = projectMapper.selectByPrimaryKey(req.getProjectId());
        boolean isAutomatic = true;
        // 项目名称或者报备图片修改，那么不进行自动同意与驳回, false为不自动进行
//        if (StringUtil.isNotBlank(req.getProjectName()) && !req.getProjectName().equals(project.getName())){
//            isAutomatic = false;
//            projectMapper.updateNameById(req.getProjectId(), req.getProjectName());
//        }
        if (StringUtil.isNotBlank(req.getPic()) && !req.getPic().equals(project.getBrandPlacementPic())) {
            isAutomatic = false;
            projectMapper.updateBrandPlacementPicById(req.getProjectId(), req.getPic());
        }
        if (StringUtil.isNotBlank(req.getMediumIds())) {
            String[] mediumIds = req.getMediumIds().split(",");
            projectIntendedMediaManageService.doAddIntendedMedia(mediumIds, req.getProjectId(), isAutomatic);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doSureCheckProjectAndSure(int projectId, Date date, int userId, Integer fileId, short userType, String productName,
                                                      String invoiceCompany,
                                                      BigDecimal invoicePrice,
                                                      String orderNo) {

        fileManageService.doSureFinalFile(fileId, userId, userType);
        doSureCheckProject(projectId, date, userId, productName, invoiceCompany, invoicePrice, orderNo);
        return APPResultMessage.getSuccessMessage();
    }

    @Transactional
    public APPResultMessage doSurePackage(int projectId, int userId, Integer fileId, short userType, BigDecimal estimatedSelfMediaCost, BigDecimal estimatedExternalMediaCost) {

        fileManageService.doSureFinalFile(fileId, userId, userType);
        MjOrder mjOrder = orderMapper.selectOne(
                new LambdaQueryWrapper<MjOrder>()
                        .eq(MjOrder::getProjectId, projectId)
                        .notIn(MjOrder::getStatus, 9, 10, 11)
                        .isNull(MjOrder::getParentId)
        );
        mjOrder.setEstimatedSelfMediaCost(estimatedSelfMediaCost);
        mjOrder.setEstimatedExternalMediaCost(estimatedExternalMediaCost);
        orderMapper.updateByPrimaryKeySelective(mjOrder);
        return APPResultMessage.getSuccessMessage();
    }

    @Transactional
    public APPResultMessage startExecute(int projectId) {

        MjProjectStage stage = projectStageMapper.selectOne(
                new LambdaQueryWrapper<MjProjectStage>()
                        .eq(MjProjectStage::getProjectId, projectId)
                        .eq(MjProjectStage::getIsCurrent, 1)
        );
        if (!stage.getCode().equals(ProjectStatusEnum.EXECUTING.getCode())) {
            MjProjectStage mjProjectStage = new MjProjectStage();


            mjProjectStage.setProjectId(projectId);
            mjProjectStage.setIsCurrent(true);
            mjProjectStage.setName(ProjectStatusEnum.EXECUTING.getName());
            mjProjectStage.setCode(ProjectStatusEnum.EXECUTING.getCode());
            mjProjectStage.setSort(stage.getSort() + 1);
            mjProjectStage.setCreateTime(new Date());

            stage.setIsCurrent(false);
            stage.setEndTime(new Date());

            projectStageMapper.insert(mjProjectStage);
            projectStageMapper.updateById(stage);
        }
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage completeExecute(int projectId, BigDecimal actualCost, Date executeDate) {
        MjOrder mjOrder = orderMapper.selectOne(
                new LambdaQueryWrapper<MjOrder>()
                        .eq(MjOrder::getProjectId, projectId)
                        .notIn(MjOrder::getStatus, 9, 10, 11)
                        .isNull(MjOrder::getParentId)
        );
        mjOrder.setActualCost(actualCost);
        orderMapper.updateById(mjOrder);

        projectMapper.updateFinalTimeByProjectId(projectId, executeDate);

        MjProjectStage stage = projectStageMapper.selectOne(
                new LambdaQueryWrapper<MjProjectStage>()
                        .eq(MjProjectStage::getProjectId, projectId)
                        .eq(MjProjectStage::getIsCurrent, 1)
        );
        if (!stage.getCode().equals(ProjectStatusEnum.EXECUTED.getCode())) {
            MjProjectStage mjProjectStage = new MjProjectStage();


            mjProjectStage.setProjectId(projectId);
            mjProjectStage.setIsCurrent(true);
            mjProjectStage.setName(ProjectStatusEnum.EXECUTED.getName());
            mjProjectStage.setCode(ProjectStatusEnum.EXECUTED.getCode());
            mjProjectStage.setSort(stage.getSort() + 1);
            mjProjectStage.setCreateTime(new Date());

            stage.setIsCurrent(false);
            stage.setEndTime(new Date());

            projectStageMapper.insert(mjProjectStage);
            projectStageMapper.updateById(stage);


        }
        return APPResultMessage.getSuccessMessage();

    }

    public APPResultMessage getCompleteExecute(int projectId) {
        MjOrder mjOrder = orderMapper.selectOne(
                new LambdaQueryWrapper<MjOrder>()
                        .eq(MjOrder::getProjectId, projectId)
                        .notIn(MjOrder::getStatus, 9, 10, 11)
                        .isNull(MjOrder::getParentId)
        );
        MjProject mjProject = projectMapper.selectById(projectId);
        completeExecuteVO completeExecuteVO = new completeExecuteVO();
        completeExecuteVO.setExecuteDate(mjProject.getFailTime());
        completeExecuteVO.setActualCost(mjOrder.getActualCost());
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(completeExecuteVO);
        successMessage.setResult(resultMessage);
        return successMessage;
    }
}
